import os
from django.shortcuts import render, HttpResponse,redirect
from app01.utils.form import UpForm,UpModelForm
from app01 import models
from django.conf import settings

def upload_list(request):
    """上传文件"""
    if request.method == "GET":
        return render(request, "upload_list.html")
    # print(request.POST)  # 请求体中的数据<QueryDict: {'csrfmiddlewaretoken': ['rUgQC4CEdv3vHiWc1v6z8M23TdYHYRNsy6mRqEeYA5HbhJWWz4lXaZNZQCHMAaN7'], 'username': ['123'], 'avator': ['a50f4bfbfbedab643b8ac351f636afc378311ea2.jpg']}>
    # print(request.FILES)  # 请求体发送过来的文件{<MultiValueDict: {}>}
    file_object = request.FILES.get("avator")
    # print(file_object.name)  # 文件名
    f = open(file_object.name, mode='wb')
    # 将文件分块读取并保存在本地文件a1.png中
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()
    return HttpResponse("---")


def upload_form(request):
    """Form上传"""
    title = "Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request, 'upload_form.html', {'form': form, "title": title})

    form = UpForm(data=request.POST, files=request.FILES)  # 提交的数据既有文件还有表单
    if form.is_valid():
        # print(form.cleaned_data)
        # {'name': '刘备', 'age': 123, 'img': <InMemoryUploadedFile: 黑曼巴.jpg (image/jpeg)>}

        # 1、读取图片内容，写入到文件夹中并获取文件的路径。
        image_object = form.cleaned_data.get("img")

        #media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        media_path = os.path.join("media", image_object.name)
        f = open(media_path,mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        # 2、将能让用户看到的图片文件的路径写入到数据库。
        models.Boss.objects.create(
            name=form.cleaned_data["name"],
            age=form.cleaned_data["age"],
            img=media_path,
        )
        return HttpResponse("……")
    return render(request, 'upload_form.html', {"form": form, "title": title})


def upload_modelform(request):
    """ModelForm上传文件和数据"""
    title="ModelForm上传"
    if request.method == "GET":
        form = UpModelForm()
        return render(request, 'upload_modelform.html',{"title":title,'form':form})
    form = UpModelForm(data=request.POST,files = request.FILES)
    if form.is_valid():
        #对应文件自动保存
        #字段+上传路径写入到数据库
        form.save()
        return redirect("/city/list/")
    return render(request, 'upload_modelform.html', {"title": title, 'form': form})